package cn.yuemouren.queue.leetcode;

import java.util.Comparator;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.TreeMap;

/**
 * @Author: Timi
 * @Description: 运用java中的优先对列实现
 * @Date: 2020/7/6 8:40
 */
public class ValidParenthesis_347_java {

    public int[] topKFrequent(int[] nums, int k) {
        //统计数字出现频次
        Map<Integer,Integer> map = new TreeMap<>();
        for (int num : nums){
            if(map.containsKey(num)){
                map.put(num,map.get(num) + 1);
            } else {
                map.put(num,1);
            }
        }
        PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer param1, Integer param2) {
                return map.get(param1) - map.get(param2);
            }
        });
        map.forEach((key,value) -> {
            if(queue.size() < k){
                queue.add(key);
            } else if(map.get(key) > map.get(queue.peek())){
                queue.remove();
                queue.add(key);
            }
        });
        int[] result = new int[queue.size()];
        for (int i = 0; i < result.length; i++){
            result[i] = queue.poll();
        }
        return result;
    }
}
